package com.caipos.ruleNode;


import com.caipos.actor.api.KbContext;
import com.caipos.actor.api.KbNode;
import com.caipos.actor.common.data.msg.KbNodeConnectionType;
import com.caipos.actor.common.msg.KbMsg;

public abstract class KbAbstractExternalNode implements KbNode {

    private boolean forceAck;

    public void init(KbContext ctx) {
        this.forceAck = ctx.isExternalNodeForceAck();
    }

    protected void tellSuccess(KbContext ctx, KbMsg KbMsg) {
        if (forceAck) {
            ctx.enqueueForTellNext(KbMsg.copyWithNewCtx(), KbNodeConnectionType.SUCCESS);
        } else {
            ctx.tellSuccess(KbMsg);
        }
    }

    protected void tellFailure(KbContext ctx, KbMsg KbMsg, Throwable t) {
        if (forceAck) {
            if (t == null) {
                ctx.enqueueForTellNext(KbMsg.copyWithNewCtx(), KbNodeConnectionType.FAILURE);
            } else {
                ctx.enqueueForTellFailure(KbMsg.copyWithNewCtx(), t);
            }
        } else {
            if (t == null) {
                ctx.tellNext(KbMsg, KbNodeConnectionType.FAILURE);
            } else {
                ctx.tellFailure(KbMsg, t);
            }
        }
    }

    protected KbMsg ackIfNeeded(KbContext ctx, KbMsg msg) {
        if (forceAck) {
            ctx.ack(msg);
            return msg.copyWithNewCtx();
        } else {
            return msg;
        }
    }

}
